//
//  DetailsSpecialTableViewController.m
//  TeamProject_Travel
//
//  Created by lanou3g on 16/3/29.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "DetailsSpecialTableViewController.h"
#import "CDHttpHelper.h"
#import "Singleton.h"
#import "DetailsSpecialModel.h"
#import "DetailsSpecialCell.h"
#import "DetailsWordsCell.h"
#import "UIImageView+WebCache.h"
#import "UINavigationBar+Awesome.h"

#define NAVBAR_CHANGE_POINT 50

static NSString *imageIdentifier = @"DetailsSpecial";
static NSString *wordsIdentifier = @"DetailsWords";

@interface DetailsSpecialTableViewController ()

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *image_url;
@property(nonatomic,copy)NSString *aTitle;

@end

@implementation DetailsSpecialTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    
    [self handleData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailsSpecialCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:imageIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailsWordsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:wordsIdentifier];
    
}

- (void)handleData
{
    self.allDataArray = [NSMutableArray array];
    Singleton *single = [Singleton shareSingle];
    
    [[CDHttpHelper defaultCDHttpHelper]get:[NSString stringWithFormat:@"https://chanyouji.com/api/articles/%ld.json?page=1",single.specialID]params:nil success:^(id responseObj) {
        NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:&error];
        
        self.name = dictionary[@"name"];
        self.image_url = dictionary[@"image_url"];
        self.aTitle = dictionary[@"title"];
        
        for (NSDictionary *dict in dictionary[@"article_sections"]) {
            
            DetailsSpecialModel *model = [[DetailsSpecialModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            for (NSString *key in dict) {
                if ([key isEqualToString:@"note"]) {
                    NSDictionary *dic = dict[@"note"];
                    [model setValuesForKeysWithDictionary:dic];
                }
            }
            [self.allDataArray addObject:model];
        }
        [self.allDataArray removeLastObject];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allDataArray.count;
}

- (void)tableViewHeaderView
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.image_url]];
    
    UILabel *nameLabel= [[UILabel alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height / 5, self.view.frame.size.width, self.view.frame.size.height / 25)];
    nameLabel.font = [UIFont fontWithName:@"Helvetica" size:24];
    nameLabel.text = self.name;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [imageView addSubview:nameLabel];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height  / 4, self.view.frame.size.width, self.view.frame.size.height / 30)];
    titleLabel.font = [UIFont fontWithName:@"Helvetica" size:17];
    titleLabel.text = self.aTitle;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [imageView addSubview:titleLabel];
    
    self.tableView.tableHeaderView = imageView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // tableHeaderView
    [self tableViewHeaderView];
    
    DetailsSpecialModel *model = [[DetailsSpecialModel alloc]init];
    model = self.allDataArray[indexPath.row];
    
    // 有文字和图片
    if (![model.image_url isEqualToString:@""]) {
        DetailsSpecialCell *cell = [tableView dequeueReusableCellWithIdentifier:imageIdentifier forIndexPath:indexPath];
        
        if (cell == nil) {
            cell = [[DetailsSpecialCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:imageIdentifier];
        }
        // 设定cell点击不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.image_urlView sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
        [cell.image_urlView setContentScaleFactor:[[UIScreen mainScreen] scale]];
        cell.image_urlView.contentMode =  UIViewContentModeScaleAspectFill;
        cell.image_urlView.clipsToBounds  = YES;
        cell.image_urlView.layer.cornerRadius = 5;
        cell.image_urlView.layer.masksToBounds = YES;
        
        cell.descriptionLabel.text = model.Description;
        cell.descriptionLabel.frame = CGRectMake(CGRectGetMinX(cell.descriptionLabel.frame), CGRectGetMinY(cell.descriptionLabel.frame), CGRectGetWidth(cell.descriptionLabel.frame), [self getTrueHeightWithDescription:model.Description fontOfSize:15]);
        
        return cell;
    
    // 标题和文字
    } else {
        DetailsWordsCell *cell = [tableView dequeueReusableCellWithIdentifier:wordsIdentifier forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[DetailsWordsCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:wordsIdentifier];
        }
        // 设定cell点击不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.titleLable.text = model.title;
        
        cell.descriptionLabel.text = model.Description;
        cell.descriptionLabel.frame = CGRectMake(CGRectGetMinX(cell.descriptionLabel.frame), CGRectGetMinY(cell.descriptionLabel.frame), CGRectGetWidth(cell.descriptionLabel.frame), [self getTrueHeightWithDescription:model.Description fontOfSize:15]);
        return cell;
    }
}

// 自适应高度
- (CGFloat)getTrueHeightWithDescription:(NSString *)discuss fontOfSize:(NSInteger)size
{
    CGRect rect = [discuss boundingRectWithSize:(CGSizeMake([UIScreen mainScreen].bounds.size.width, 2000000)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size]} context:nil];
    return rect.size.height;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsSpecialModel *model = [[DetailsSpecialModel alloc]init];
    model = self.allDataArray[indexPath.row];
    
    if (![model.image_url isEqualToString:@""]) {
        return [self getTrueHeightWithDescription:model.Description fontOfSize:15] + 300;
    } else {
        return [self getTrueHeightWithDescription:model.Description fontOfSize:15] + 100;
    }
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor * color = [UIColor colorWithRed:0 green:191/255.0 blue:255/255.0 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar lt_reset];
}

@end
